package com.example.schedulemanager.repository;

import android.app.Application;

import androidx.lifecycle.LiveData;

import com.example.schedulemanager.database.ScheduleDatabase;
import com.example.schedulemanager.database.ScheduleDao;
import com.example.schedulemanager.model.Schedule;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

public class ScheduleRepository {
    
    private ScheduleDao scheduleDao;
    private LiveData<List<Schedule>> allSchedules;
    private ExecutorService executorService;
    
    public ScheduleRepository(Application application) {
        ScheduleDatabase database = ScheduleDatabase.getDatabase(application);
        scheduleDao = database.scheduleDao();
        allSchedules = scheduleDao.getAllSchedules();
        executorService = Executors.newSingleThreadExecutor();
    }
    
    public void insert(Schedule schedule, Consumer<Long> callback) {
        executorService.execute(() -> {
            long id = scheduleDao.insert(schedule);
            if (callback != null) {
                new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> callback.accept(id));
            }
        });
    }
    
    public void update(Schedule schedule) {
        executorService.execute(() -> scheduleDao.update(schedule));
    }
    
    public void delete(Schedule schedule) {
        executorService.execute(() -> scheduleDao.delete(schedule));
    }
    
    public LiveData<List<Schedule>> getAllSchedules() {
        return allSchedules;
    }
    
    public LiveData<List<Schedule>> getSchedulesByDate(String date) {
        return scheduleDao.getSchedulesByDate(date);
    }
    
    public LiveData<List<Schedule>> getUpcomingSchedules(String currentDate) {
        return scheduleDao.getUpcomingSchedules(currentDate);
    }
    
    public void getScheduleById(int id, Consumer<Schedule> callback) {
        executorService.execute(() -> {
            Schedule schedule = scheduleDao.getScheduleById(id);
            if (callback != null) {
                new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> callback.accept(schedule));
            }
        });
    }
    
    public void updateCompletionStatus(int id, boolean completed) {
        executorService.execute(() -> scheduleDao.updateCompletionStatus(id, completed));
    }
} 